package org.realogic.cfm.persistence.query;

import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;

import org.realogic.cfm.persistence.KParameter;
import org.realogic.cfm.persistence.KSqlParameter;
import org.realogic.cfm.persistence.element.KDoubleElement;
import org.realogic.cfm.persistence.element.KFloatElement;
import org.realogic.cfm.persistence.element.KIntegerElement;
import org.realogic.cfm.persistence.element.KLongElement;
import org.realogic.cfm.persistence.element.KSqlDateElement;
import org.realogic.cfm.persistence.element.KSqlTimeElement;
import org.realogic.cfm.persistence.element.KSqlTimestampElement;
import org.realogic.cfm.persistence.element.KStringElement;

public final class SqlParameterFactory {

	public static KParameter buildParameter(String theValue, String theType, String theParamterName) {
		KParameter tmp = null;
		if (theType.equalsIgnoreCase("str")) {
			tmp = new KSqlParameter(theParamterName, new KStringElement(theValue));
		} else if (theType.equalsIgnoreCase("int")) {
			tmp = new KSqlParameter(theParamterName, new KIntegerElement(Integer.parseInt(theValue)));
		} else if (theType.equalsIgnoreCase("float")) {
			tmp = new KSqlParameter(theParamterName, new KFloatElement(Float.parseFloat(theValue)));
		} else if (theType.equalsIgnoreCase("double")) {
			tmp = new KSqlParameter(theParamterName, new KDoubleElement(Double.parseDouble(theValue)));
		} else if (theType.equalsIgnoreCase("long")) {
			tmp = new KSqlParameter(theParamterName, new KLongElement(Long.parseLong(theValue)));
		} else if (theType.equalsIgnoreCase("date")) {
			tmp = new KSqlParameter(theParamterName, new KSqlDateElement(Date.valueOf(theValue)));
		} else if (theType.equalsIgnoreCase("timestamp")) {
			tmp = new KSqlParameter(theParamterName, new KSqlTimestampElement(Timestamp.valueOf(theValue)));
		} else if (theType.equalsIgnoreCase("time")) {
			tmp = new KSqlParameter(theParamterName, new KSqlTimeElement(Time.valueOf(theValue)));
		} else if (theType.equalsIgnoreCase("timeS")) {
			tmp = new KSqlParameter(theParamterName, new KSqlTimeElement(Time.valueOf(theValue)));
		} else if (theType.equalsIgnoreCase("timeE")) {
			tmp = new KSqlParameter(theParamterName, new KSqlTimeElement(timeE(Time.valueOf(theValue))));
		} else if (theType.equalsIgnoreCase("timestampS")) {
			tmp = new KSqlParameter(theParamterName, new KSqlTimestampElement(Timestamp.valueOf(theValue + " 0:0:0")));
		} else if (theType.equalsIgnoreCase("timestampE")) {
			tmp = new KSqlParameter(theParamterName, new KSqlTimestampElement(Timestamp.valueOf(theValue + " 24:0:0")));
		} else {
			throw new IllegalArgumentException("[Type=" + theType + "] unsupported");
		}
		return tmp;
	}

	public static Time timeE(Time theTime) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(theTime);
		calendar.add(Calendar.SECOND, 1);
		return new java.sql.Time(calendar.getTimeInMillis());
	}
}
